package com.enjoy.xbase.nest;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;

/**
 * 描述：嵌套滑动父级类
 */
public class ParentScrollView extends ScrollView {
    private int mLastX;
    private int mLastY;
    private int mLastX1;
    private int mLastY1;
    private NestListener nestListener;


    public ParentScrollView(Context context) {
        super(context);
    }

    public ParentScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ParentScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setNestListener(NestListener nestListener) {
        this.nestListener = nestListener;
    }

    /**
     * @return 是否滑动到底部
     */
    public boolean isToBottom(){
        if(getScrollY() +getHeight() == computeVerticalScrollRange()){//
            return true;
        }else{
            return false;
        }
    }
    public boolean isToTop(){
        return getScrollY()==0;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        //默认不拦截
        boolean intercepted = false;
        switch (ev.getActionMasked()) {
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_DOWN:
                intercepted = false;
                super.onInterceptTouchEvent(ev);
                break;
            case MotionEvent.ACTION_MOVE:
                int deltaX = (int) (ev.getX() - mLastX);
                int deltaY = (int) (ev.getY() - mLastY);
                if (nestListener!=null&&nestListener.allowParent(deltaX,deltaY)){
                    intercepted = true;
                }else{
                    intercepted = false;
                }
                break;
        }
        mLastX = (int) ev.getX();
        mLastY = (int) ev.getY();
        return intercepted;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getActionMasked()){
            case MotionEvent.ACTION_MOVE:
                int deltaX = (int) (ev.getX() - mLastX1);
                int deltaY = (int) (ev.getY() - mLastY1);
                if (nestListener!=null&& (!nestListener.allowParent(deltaX,deltaY))){
                    //requestDisallowInterceptTouchEvent(false);
                    mLastX1 = (int) ev.getX();
                    mLastY1 = (int) ev.getY();
                    return false;
                }
                break;
        }
        mLastX1 = (int) ev.getX();
        mLastY1 = (int) ev.getY();
        return super.onTouchEvent(ev);
    }
}
